package cn.edu.ahu.aircondition.modbus.service.serviceImpl;

import cn.edu.ahu.aircondition.modbus.service.domain.CtrlRegDomain;
import cn.edu.ahu.aircondition.modbus.service.domain.QueryRegDomain;
import cn.edu.ahu.aircondition.modbus.service.domain.Response;
import cn.edu.ahu.aircondition.modbus.service.service.AirConDataDecodeService;
import cn.edu.ahu.aircondition.modbus.service.service.ModReadAndWriteSer;
import cn.edu.ahu.aircondition.modbus.service.util.HttpRequest;
import cn.edu.ahu.aircondition.modbus.service.util.ModbusReadAWriteUtil;
import cn.edu.ahu.aircondition.modbus.service.util.XmlUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 *
 * Created by ahu on 2017/6/6.
 */
public class ModReadAndWriteSerImpl implements ModReadAndWriteSer {
    private AirConDataDecodeService airConDataDecodeService = new AirConDataDecodeServiceImpl();
    /**
     * 根据设置Domain，设置上位机的寄存器
     * @param ctrlDomain 设置好的控制Domain
     * @return 包含控制结果的Response
     */
    public Response setCtrlToReg(CtrlRegDomain ctrlDomain){
        try {
            ModbusReadAWriteUtil writeUtil = new ModbusReadAWriteUtil();
            return new Response().success(writeUtil.WriteModbusByTCP(ctrlDomain.getCtrlMap()));
        }
        catch (Exception e){
            return new Response().failure(e.getMessage());
        }
    }

    /**
     * 根据设备的Address获取包含设备状态的Response
     * @param address 设备Address
     * @return 包含设备n的状态的Response
     */
    public Response getQueryFromReg(Integer address) throws Exception{
        try {
            Properties prop = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream("Bobei\\src\\main\\resource\\config.properties"));
            prop.load(in);
            String url = "http://" + prop.getProperty("url") + "/ctrl.xml";
            String add = "u=" + String.valueOf(address);
            String data = HttpRequest.sendGet(url,add.trim());
            Document document = DocumentHelper.parseText(data);
            Element root = document.getRootElement();
            // 循环子节点，开始向map中存值
            Map<String, Object> responseMap = XmlUtil.element2Map(root);
            String responseData = responseMap.get("ret").toString().trim();
            List<Integer> airConData = airConDataDecodeService.getData(responseData);
            QueryRegDomain queryRegDomain = new QueryRegDomain(address,
                    airConData.subList(0,81),
                    airConData.subList(130,132));
            return new Response().success(queryRegDomain);
        }
        catch (Exception e){
            return new Response().failure(e.getMessage());
        }
    }
}
